﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace P2P_Backup.archive
{
    public class FolderArgs : EventArgs
    {
        public FolderArgs(Folder folder)
        {
            this.folder = folder;
        }
        private Folder folder;
        public Folder Folder
        {
            get { return folder; }
        }
    }
    
    public class Folder
    {
        public String Name = "";
        public List<Folder> Folders;
        public List<File> Files;
        public Folder()
        {
            Folders = new List<Folder>();
            Files = new List<File>();
        }
        public Folder(String path)
        {            
            Folders = new List<Folder>();
            Files = new List<File>();
            Name = path.Substring(path.LastIndexOf('\\') + 1);
            foreach (String dir in System.IO.Directory.GetDirectories(path))
            {
                addFolder(new Folder(dir));
            }
            foreach (String file in System.IO.Directory.GetFiles(path))
            {
                addFile(new File(file));
            }
        }

        public event EventHandler<FolderArgs> FolderAdded;
        public void addFolder(Folder folder)
        {
            Folders.Add(folder);            
            if (FolderAdded != null) FolderAdded(this, new FolderArgs(folder));
        }

        public event EventHandler<FileArgs> FileAdded;
        public void addFile(File file)
        {
            Files.Add(file);            
            if (FileAdded != null) FileAdded(this, new FileArgs(file));
        }

        public event EventHandler<FolderArgs> FolderRemoved;
        public void removeFolder(Folder folder)
        {
            Folders.Remove(folder);            
            if (FolderRemoved != null) FolderRemoved(this, new FolderArgs(folder));
        }

        public event EventHandler<FileArgs> FileRemoved;
        public void removeFile(File file)
        {
            Files.Remove(file);
            if (FileRemoved != null) FileRemoved(this, new FileArgs(file));
        }

        public override string ToString()
        {
            return Name;
        }
        public Folder getFolderForPeer(Peer peer)
        {
            Folder result = new Folder();
            foreach(Folder folder in Folders)
                result.Folders.Add(folder.getFolderForPeer(peer));
            result.Files.AddRange(this.Files.Where(f => f.BackupPeer.Equals(peer) && f.Status == TransferStatus.Complete));

            return result;         
        }
        public File FindFile(string fileId)
        {
            File result = this.Files.Find(i => i.Id.Equals(new Guid(fileId)));
            if (result == null)
                foreach (archive.Folder f in this.Folders)
                    f.FindFile(fileId);
            return result;
        }
    }
}
